using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using UniversalAdmin.Domain.Common;
using UniversalAdmin.Domain.Events;

namespace UniversalAdmin.Domain.Entities;

[Table("menus")]
public class Menu : AggregateRoot
{
  [Required]
  [MaxLength(100)]
  [Column("name")]
  public string Name { get; private set; } = null!;// 菜单名称

  [MaxLength(255)]
  [Column("path")]
  public string? Path { get; private set; }// 菜单路径

  [MaxLength(50)]
  [Column("icon")]
  public string? Icon { get; private set; } // 菜单图标

  [Column("parent_id")]
  public int? ParentId { get; private set; }// 父级菜单ID

  [ForeignKey("ParentId")]
  public virtual Menu? ParentMenu { get; set; }// 父级菜单

  [Column("sort")]
  public int Sort { get; set; } = 0;

  // 导航属性
  public virtual ICollection<Menu> Children { get; private set; } = new List<Menu>();

  public virtual ICollection<RoleMenu> RoleMenus { get; set; } = new List<RoleMenu>();

  // EF Core 用
  private Menu() { }

  // 工厂
  public static Menu Create(
      string name,
      string? path,
      string? icon,
      int? parentId,
      int? sort = null)
  {
    if (string.IsNullOrWhiteSpace(name))
      throw new ArgumentException("菜单名称不能为空");

    var menu = new Menu
    {
      Name = name,
      Path = path,
      Icon = icon,
      ParentId = parentId,
      Sort = sort ?? 0
    };

    menu.AddDomainEvent(new MenuCreatedEvent(menu));
    return menu;
  }

  // 领域行为
  public void UpdateDetails(string name, string? path, string? icon, int? parentId,int sort)
  {
    Name = name;
    Path = path;
    Icon = icon;
    ParentId = parentId;
    UpdatedAt = DateTime.UtcNow;
    Sort=sort;

    AddDomainEvent(new MenuUpdatedEvent(this));
  }

  public void Delete()
  {
    IsActive = false;
    UpdatedAt = DateTime.UtcNow;

    AddDomainEvent(new MenuDeletedEvent(Id, Name));
  }

  public void ChangeSort(int newSort)
  {
    var old = Sort;
    Sort = newSort;
    UpdatedAt = DateTime.UtcNow;

    AddDomainEvent(new MenuSortChangedEvent(this, old));
  }
}